package com.xm.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.xm.common.constant.CommonConstant;
import com.xm.common.HttpSingleton;
import com.xm.entity.HomeInfoEntity;
import com.xm.entity.HomeInfoNewEntity;
import com.xm.service.GetXmGoodsService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;


/**
 * @Author tianqin
 * @Date 2024/7/29 13:41
 * 具体实现类
 */
@Service
public class GetXmGoodsServiceImpl implements GetXmGoodsService {

    /**
     * 获取用户当前的矿币余额
     * @param token
     * @return
     */
    @Override
    public String getUserScore(String token) {
        long startTime = System.currentTimeMillis();
        JSONObject json = new JSONObject();
        json.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1");
        json.put("Sec-Fetch-Site","same-site");
        json.put("Sec-Fetch-Mode","cors");
        json.put("Sec-Fetch-Dest","empty");
        HttpClient httpClient = HttpSingleton.getInstance();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(USER_SCORE))
                .header("Content-Type", "application/json")
                .header("token", token)
                .POST(HttpRequest.BodyPublishers.ofString(json.toString()))
                .build();
        // 构建本次请求返回结果
        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            JSONObject jsonObject = new JSONObject(response.body());
            Integer code = jsonObject.getInt("code");
            Object dataObject = jsonObject.get("data");
            JSONObject userinfoObject = ((JSONObject) dataObject).getJSONObject("userinfo");
            String score = userinfoObject.getString("score");
            System.out.println("score: " + score);
            long methodCostTime = System.currentTimeMillis() - startTime;
            return String.format("方法执行时间为:{%s},耗时为:{%s},本次请求返回状态码为:%s,返回信息为---->%s", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), methodCostTime,code,score);
        }catch (Exception e){
            System.out.println(e);
            return e.getMessage();
        }
    }

    /**
     * 获取首页当前的数据列表
     */
    @Override
    public List<HomeInfoNewEntity> getGoodsList(String passCode, String shopName) {
        JSONObject json = new JSONObject();
        json.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1");
        json.put("Sec-Fetch-Site","same-site");
        json.put("Sec-Fetch-Mode","cors");
        json.put("Sec-Fetch-Dest","empty");
        HttpClient httpClient = HttpSingleton.getInstance();
//        HttpRequest request = HttpRequest.newBuilder()
//                .uri(URI.create(GOODS_LIST))
//                .header("Content-Type", "application/json")
//                .header("Authorization",passCode)
//                .POST(HttpRequest.BodyPublishers.ofString("{\"minPrice\":null,\"issueDay\":null,\"seriesName\":null,\"isUpAsc\":null,\"search\":null,\"isTransfer\":1,\"platformId\":894,\"isPrizeAsc\":null,\"pageNum\":1,\"pageSize\":100,\"searchType\":null}"))
//                .build();
        HttpRequest request_new = HttpRequest.newBuilder()
                .uri(URI.create(GOODS_LIST_NEW))
                .header("Content-Type", "application/json")
                .header("Authorization",passCode)
                .POST(HttpRequest.BodyPublishers.ofString("{\"platformIds\":[],\"pageNum\":1,\"type\":\"\",\"search\":\""+shopName+"\",\"isTransfer\":\"\",\"goodsTypeList\":[2,3]}"))
                .build();
        // 构建本次请求返回结果
        List<HomeInfoNewEntity> goodsList = Collections.emptyList();
        try {
            HttpResponse<String> response = httpClient.send(request_new, HttpResponse.BodyHandlers.ofString());
            JSONObject jsonObject = new JSONObject(response.body());
            if (CommonConstant.SUCCESS_CODE == jsonObject.getInt("code")){
                JSONArray data = jsonObject.getJSONArray("data");
                ObjectMapper objectMapper = new ObjectMapper();
                CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, HomeInfoNewEntity.class);
                goodsList = objectMapper.readValue(data.toString(), collectionType);
            }
        }catch (Exception e){
            System.out.println("转换实体类错误"+e);
        }
        return goodsList;
    }

}
